<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>STM32学习——看门狗 | XiaoZiYan</title><meta name="keywords" content="学习,单片机,STM32&quot;"><meta name="author" content="XiaoZiYan"><meta name="copyright" content="XiaoZiYan"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="学习stm32单片机">
<meta property="og:type" content="article">
<meta property="og:title" content="STM32学习——看门狗">
<meta property="og:url" content="https://xiaoziyanxiaoludan.gitee.io/xiaoziyan/2019/11/10/STM32%E5%AD%A6%E4%B9%A0%E2%80%94%E2%80%94%E5%88%9D%E8%AF%86stm32/index.html">
<meta property="og:site_name" content="XiaoZiYan">
<meta property="og:description" content="学习stm32单片机">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://xiaoziyan.top/images/dog1.jpg">
<meta property="article:published_time" content="2019-11-10T12:12:02.000Z">
<meta property="article:modified_time" content="2022-11-03T10:27:40.109Z">
<meta property="article:author" content="XiaoZiYan">
<meta property="article:tag" content="学习">
<meta property="article:tag" content="单片机">
<meta property="article:tag" content="STM32&quot;">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://xiaoziyan.top/images/dog1.jpg"><link rel="shortcut icon" href="/xiaoziyan/img/favicon.png"><link rel="canonical" href="https://xiaoziyanxiaoludan.gitee.io/xiaoziyan/2019/11/10/STM32%E5%AD%A6%E4%B9%A0%E2%80%94%E2%80%94%E5%88%9D%E8%AF%86stm32/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><meta/><link rel="stylesheet" href="/xiaoziyan/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/xiaoziyan/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":50,"languages":{"author":"作者: XiaoZiYan","link":"链接: ","source":"来源: XiaoZiYan","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#121212","position":"bottom-left"},
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: true,
  islazyload: false,
  isanchor: true
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'STM32学习——看门狗',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-11-03 18:27:40'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if (GLOBAL_CONFIG_SITE.isHome && /iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="./css/custom.css" media="defer" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome/css/font-awesome.min.css"><!-- hexo injector head_end start --><link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/Zfour/hexo-electric-clock@1.0.6/clock.css"><!-- hexo injector head_end end --><meta name="generator" content="Hexo 5.4.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/xiaoziyan/img/avatar.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/xiaoziyan/archives/"><div class="headline">文章</div><div class="length-num">33</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/xiaoziyan/tags/"><div class="headline">标签</div><div class="length-num">41</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/xiaoziyan/categories/"><div class="headline">分类</div><div class="length-num">39</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/xiaoziyan/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/xiaoziyan/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/xiaoziyan/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/xiaoziyan/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 多媒体</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/xiaoziyan/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/xiaoziyan/movies/"><i class="fa-fw fas fa-video"></i><span> 视频</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/xiaoziyan/link/"><i class="fa-fw fas fa-link"></i><span> 友情链接</span></a></div><div class="menus_item"><a class="site-page" href="/xiaoziyan/about/"><i class="fa-fw fas fa-heart"></i><span> 关于我</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('http://xiaoziyan.top/images/dog1.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/xiaoziyan/">XiaoZiYan</a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/xiaoziyan/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/xiaoziyan/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/xiaoziyan/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/xiaoziyan/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 多媒体</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/xiaoziyan/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/xiaoziyan/movies/"><i class="fa-fw fas fa-video"></i><span> 视频</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/xiaoziyan/link/"><i class="fa-fw fas fa-link"></i><span> 友情链接</span></a></div><div class="menus_item"><a class="site-page" href="/xiaoziyan/about/"><i class="fa-fw fas fa-heart"></i><span> 关于我</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">STM32学习——看门狗</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2019-11-10T12:12:02.000Z" title="发表于 2019-11-10 20:12:02">2019-11-10</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-11-03T10:27:40.109Z" title="更新于 2022-11-03 18:27:40">2022-11-03</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/xiaoziyan/categories/%E5%AD%A6%E4%B9%A0/">学习</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/xiaoziyan/categories/%E5%AD%A6%E4%B9%A0/stm32/">stm32</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/xiaoziyan/categories/%E5%AD%A6%E4%B9%A0/stm32/%E5%8D%95%E7%89%87%E6%9C%BA/">单片机</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="STM32学习——看门狗"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><p>STM32的看门狗有俩个 WWDG和IWDG 两者最大的区别就是IWDG只有一个喂食下限而WWDG顾名思义窗户必须在一个范围内喂食才能保证不会触发复位</p>
<h3 id="一-IWDG（独立看门狗）"><a href="#一-IWDG（独立看门狗）" class="headerlink" title="一.IWDG（独立看门狗）"></a>一.IWDG（独立看门狗）</h3><p>1） <strong>取消寄存器写保护</strong>（ 向 IWDG_KR 写入 0X5555）通过这步，我们取消 IWDG_PR 和 IWDG_RLR 的写保护，使后面可以操作这两个寄存器,<br>设置 IWDG_PR 和 IWDG_RLR 的值。 这在库函数中的实现函数是：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">IWDG_WriteAccessCmd(IWDG_WriteAccess_Enable);</span><br></pre></td></tr></table></figure>

<p>这个函数非常简单， 顾名思义就是开启/取消写保护，也就是使能/失能写权限。<br>2）<strong>设置独立看门狗的预分频系数和重装载值</strong>，</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">IWDG_SetPrescaler</span><span class="params">(<span class="keyword">uint8_t</span> IWDG_Prescaler)</span></span>; <span class="comment">//分频系数</span></span><br><span class="line">IWDG_Prescaler_4 设置 IWDG 预分频值为 <span class="number">4</span></span><br><span class="line">IWDG_Prescaler_8 设置 IWDG 预分频值为 <span class="number">8</span></span><br><span class="line">IWDG_Prescaler_16 设置 IWDG 预分频值为 <span class="number">16</span></span><br><span class="line">IWDG_Prescaler_32 设置 IWDG 预分频值为 <span class="number">32</span></span><br><span class="line">IWDG_Prescaler_64 设置 IWDG 预分频值为 <span class="number">64</span></span><br><span class="line">IWDG_Prescaler_128 设置 IWDG 预分频值为 <span class="number">128</span></span><br><span class="line">IWDG_Prescaler_256 设置 IWDG 预分频值为 <span class="number">256</span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">IWDG_SetReload</span><span class="params">(<span class="keyword">uint16_t</span> Reload)</span></span>; <span class="comment">//重装载值0-0x0fff</span></span><br></pre></td></tr></table></figure>

<p>下面是俩个函数的资料<br>设置好看门狗的分频系数 prer 和重装载值就可以知道看门狗的喂狗时间，该时间的计算方式为：<br>Tout=((4×prer) ×rlr) /40<br>其中 Tout 为看门狗溢出时间（单位为 ms）； prer 为看门狗时钟预分频值（ IWDG_PR 值）； rlr 为看门狗的重装载值（ IWDG_RLR 的值）；<br>比如我们设定 prer 值为 16， rlr 值为 625，那么就可以得到 Tout=64×625/40=1000ms，这样，看门狗的溢出时间就是 1s。这里需要提醒大家的是，看门狗的时钟不是准确的 40Khz，所以在喂狗的时候，最好不要太晚了，否则，有可能发生看门狗复位。<br>3） <strong>重载计数值喂狗</strong>（ 向 IWDG_KR 写入 0XAAAA）库函数里面重载计数值的函数是：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">IWDG_ReloadCounter(); <span class="comment">//按照 IWDG 重装载寄存器的值重装载 IWDG 计数器</span></span><br></pre></td></tr></table></figure>

<ol start="4">
<li><strong>启动看门狗</strong>(向 IWDG_KR 写入 0XCCCC)库函数里面启动独立看门狗的函数是：</li>
</ol>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">IWDG_Enable(); <span class="comment">//使能 IWDG</span></span><br></pre></td></tr></table></figure>

<p>注意 IWDG 在一旦启用，就不能再被关闭！想要关闭，只能重启，并且重启之后不能打开 IWDG，否则问题依旧，所以在这里提醒大家，如果不<br>用 IWDG 的话，就不要去打开它，免得麻烦。<br>一般示例如下</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&quot;wdg.h&quot;</span></span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">IWDG_Init</span><span class="params">(u8 prer,u16 rlr)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">IWDG_WriteAccessCmd(IWDG_WriteAccess_Enable); <span class="comment">//①使能写操作</span></span><br><span class="line">IWDG_SetPrescaler(prer); <span class="comment">//②设置 IWDG 预分频值:设置 IWDG 预分频值</span></span><br><span class="line">IWDG_SetReload(rlr); <span class="comment">//②设置 IWDG 重装载值</span></span><br><span class="line">IWDG_ReloadCounter(); <span class="comment">//③按照 IWDG 重装载寄存器的值重装载 IWDG 计数器</span></span><br><span class="line">IWDG_Enable(); <span class="comment">//④使能 IWDG</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//喂独立看门狗</span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">IWDG_Feed</span><span class="params">(<span class="keyword">void</span>)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">IWDG_ReloadCounter();<span class="comment">//reload </span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="二-窗户看门狗"><a href="#二-窗户看门狗" class="headerlink" title="二.窗户看门狗"></a>二.窗户看门狗</h3><p>WWDG 窗户看门狗 Window Watch DoG<br>在自己的中断程序喂狗<br>1.可编程自由运行的递减计数器<br>2.复位条件： (1). 当计数器的数值从0x40减到0x3F时（2） .当刷新看门狗时计数器的数值大于窗口上限值时（窗口的值可以进行设定最大为0x7f 当喂狗时会比较窗户寄存器和递减计数器的值如果递减计数器的值大于窗口寄存器时，会发生置位就相当于设置了一个上限喂狗的时间必须在上限以下才行 这也体现了窗口这个词的含义）<br>3.若允许中断，当递减计数器等于0x40时可以产生中断，使递减计数器值被重装以避免复位</p>
<p><strong>1） 使能 WWDG 时钟</strong><br>WWDG 不同于 IWDG， IWDG 有自己独立的 40Khz 时钟，不存在使能问题。而 WWDG使用的是 PCLK1 的时钟，需要先使能时钟。 方法是:</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">RCC_APB1PeriphClockCmd(RCC_APB1Periph_WWDG, ENABLE); <span class="comment">// WWDG 时钟使能</span></span><br></pre></td></tr></table></figure>

<p><strong>2） 设置窗口值函数是：</strong></p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">WWDG_SetWindowValue</span><span class="params">(<span class="keyword">uint8_t</span> WindowValue)</span>；<span class="comment">//设置看门狗的上窗口值值在0x40-0x7f</span></span></span><br></pre></td></tr></table></figure>

<p>设置分频数的函数是：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">WWDG_SetPrescaler</span><span class="params">(<span class="keyword">uint32_t</span> WWDG_Prescaler)</span>；<span class="comment">//设置看门狗的分频值</span></span></span><br><span class="line"><span class="function">WWDG_Prescaler_1 WWDG 计数器时钟为（ PCLK/4096） /1</span></span><br><span class="line"><span class="function">WWDG_Prescaler_2 WWDG 计数器时钟为（ PCLK/4096） /2</span></span><br><span class="line"><span class="function">WWDG_Prescaler_4 WWDG 计数器时钟为（ PCLK/4096） /4</span></span><br><span class="line"><span class="function">WWDG_Prescaler_8 WWDG 计数器时钟为（ PCLK/4096） /8</span></span><br></pre></td></tr></table></figure>

<p><strong>3） 开启 WWDG 中断并分组，开启 WWDG 中断的函数为：</strong></p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">WWDG_EnableIT(); <span class="comment">//开启窗口看门狗中断</span></span><br></pre></td></tr></table></figure>

<p>再用<code>NVIC_Init()</code>函数即可。<br><strong>4） 设置计数器初始值并使能看门狗</strong></p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">WWDG_Enable</span><span class="params">(<span class="keyword">uint8_t</span> Counter)</span>；</span></span><br><span class="line"><span class="function">该参数取值必须在 0x40 与 0x7F 之间</span></span><br><span class="line"><span class="function">WWDG 一旦被使能就不能被失能</span></span><br></pre></td></tr></table></figure>

<p>该函数既设置了计数器初始值，同时使能了窗口看门狗。<br><strong>5） 编写中断服务函数</strong><br>用来保存重要的信息<br>示例</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">WWDG_Init</span><span class="params">(u8 wr,u32 fprer)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">RCC_APB1PeriphClockCmd(RCC_APB1Periph_WWDG, ENABLE); <span class="comment">// WWDG 时钟使能</span></span><br><span class="line">WWDG_SetPrescaler(fprer); <span class="comment">//设置 IWDG 预分频值</span></span><br><span class="line">WWDG_SetWindowValue(wr); <span class="comment">//设置窗口值</span></span><br><span class="line">WWDG_Enable(<span class="number">0x7f</span>); <span class="comment">//使能看门狗,设置 counter</span></span><br><span class="line">WWDG_ClearFlag(); <span class="comment">//清除提前唤醒中断标志位</span></span><br><span class="line">WWDG_NVIC_Init(); <span class="comment">//初始化窗口看门狗 NVIC</span></span><br><span class="line">WWDG_EnableIT(); <span class="comment">//开启窗口看门狗中断</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//窗口看门狗中断服务程序</span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">WWDG_NVIC_Init</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">NVIC_InitTypeDef NVIC_InitStructure;</span><br><span class="line">NVIC_InitStructure.NVIC_IRQChannel = WWDG_IRQn; <span class="comment">//WWDG 中断</span></span><br><span class="line">NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = <span class="number">2</span>; <span class="comment">//抢占 2 子优先级 3 组 2</span></span><br><span class="line">NVIC_InitStructure.NVIC_IRQChannelSubPriority = <span class="number">3</span>; <span class="comment">//抢占 2,子优先级 3,组 2</span></span><br><span class="line">NVIC_InitStructure.NVIC_IRQChannelCmd=ENABLE;</span><br><span class="line">NVIC_Init(&amp;NVIC_InitStructure); <span class="comment">//NVIC 初始化</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">WWDG_IRQHandler</span><span class="params">(<span class="keyword">void</span>)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">WWDG_SetCounter(WWDG_CNT); <span class="comment">//喂狗 在唤醒中断中喂狗在逻辑上是行不通的</span></span><br><span class="line">WWDG_ClearFlag(); <span class="comment">//清除提前唤醒中断标志位</span></span><br><span class="line">LED1=!LED1; <span class="comment">//LED 状态翻转</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>关于喂狗时间：<br>WWDG与IWDG的主要区别是有一个窗口控制，WWDG的中断是给你最后一次喂狗的机会，通常这个中断不是让你执行喂狗操作的；一般进到这个中断时表示你在其它地方安排的喂狗操作不能奏效，而发生这种现象时，肯定是系统有问题了，或者是程序有Bug，或者是碰到了干扰，在这种情况下，这个中断是为了让你的程序在发生真正的看门狗复位前，有一个紧急处理的机会，如保存重要的数据，或做系统刹车等操作。<br>由此看出，简单地在WWDG中断喂狗，既没有发挥WWDG相对于IWDG的优势，又因为在中断中喂狗而为以后的产品留下了隐患。</p>
<p><strong>几点思考：</strong><br>第一、我们可以发现即使设定了最大值，WWDG最大计时仅仅有58ms，我们在比较大的程序中也没必要运行一小段就添加一个喂狗程序，想使其定时5S或10S的时间再复位系统应该怎样处理呢？通过实验我找到一种方法，就是在中断函数中再做一个额外计数器，如果计数器没有达到设定值，就重新加载喂狗定时器初值，同时使设定值加1，当计数器达到设定值时，就不加载喂狗定时器初值，这时看门狗定时器就会从从0x40减到0x3F产生系统复位。使用这个方法可以将定时时间拓展到 58ms*额外计数器设定值，定个几十秒都不是问题</p>
<p>第二，当额外计数器达到设定值时，此时说明程序没有及时复位这个额外计数器，软件或硬件发生了错误，将时系统复位，我们需要存储一些运行过程中的变量，仅仅有不到1ms的时间（从0x40减到0x3F最长大概为910us）怎么够用呢？ </p>
<p>这样就先写Wwdg_Feed(0x7F)重新加定时器初值，再对我们的存储函数进行改造，多添加一些Wwdg_Feed(0x7F)函数，使其不至于再减到0x40，存储工作都做好之后，不再喂狗，那么再次发生中断后不再喂狗就会复位系统了。</p>
<p>第三，如果发生复位，如何区分是上电复位还是看门狗复位呢？<br>在初始化WWDG时候，有一个RCC_GetFlagStatus(RCC_FLAG_WWDGRST)可以用于判断是否发生看门狗复位，如果是重新上电引起的复位这个值当然是系统默认值，如果是看门狗复位的话这个值就会发生变化，这样就可以针对这两种不同状态进行状态恢复。</p>
<p><strong>理解</strong><br>1、有个7位递减计数器(WWDG-&gt;CR)，就这个计数器和窗口计数器(WWDG-&gt;CFR)决定什么时候喂狗。 狗喂早了，复位——“早”体现在 计数器值(tr)&gt;窗口值(wr),也就是计数器值还没有减到窗口值以下</p>
<p>2、当 0x40 &lt; 计数器值(tr) &lt; 窗口值(wr) 时，这时候最适合喂狗了，也只有在这时候喂狗才合适；</p>
<p>3、当 计数器的值 从0x40变到0x3F的时候，将产生看门狗复位；当然在要产生复位的前一段时间，如果开启了提前唤醒中断，那么就会进入中断，在中断函数里，我们需要及时喂狗，否则会产生复位；</p>
<p>4、据网上资料介绍，在这个中断里面一般不进行喂狗，一般是系统去世前的“遗嘱”，比如存储重要的数据等。这个就需要根据个人需要设计。</p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">XiaoZiYan</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a target="_blank" rel="noopener" href="https://baidu.com">https://baidu.com</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://xiaoziyanxiaoludan.gitee.io/xiaoziyan" target="_blank">XiaoZiYan</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/xiaoziyan/tags/%E5%AD%A6%E4%B9%A0/">学习</a><a class="post-meta__tags" href="/xiaoziyan/tags/%E5%8D%95%E7%89%87%E6%9C%BA/">单片机</a><a class="post-meta__tags" href="/xiaoziyan/tags/STM32/">STM32&quot;</a></div><div class="post_share"><div class="social-share" data-image="http://xiaoziyan.top/images/dog1.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/xiaoziyan/2020/09/30/%E7%88%AC%E8%99%AB%E5%AD%A6%E4%B9%A002%E2%80%94%E2%80%94%E7%99%BE%E5%BA%A6%E9%A1%B5%E9%9D%A2/"><img class="prev-cover" src="http://xiaoziyan.top/images/baidu.jpeg" onerror="onerror=null;src='/xiaoziyan/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">爬虫学习02——爬整个百度页面</div></div></a></div><div class="next-post pull-right"><a href="/xiaoziyan/2019/10/14/C51%E5%8D%95%E7%89%87%E6%9C%BA%E5%AD%A6%E4%B9%A0%E2%80%94%E2%80%94ADC%E3%80%81PWM/"><img class="next-cover" src="http://xiaoziyan.top/images/f45614980b681dfbe655f12e7ba148cd.jpeg" onerror="onerror=null;src='/xiaoziyan/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">C51单片机学习——ADC/PWM</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/xiaoziyan/2019/10/14/C51%E5%8D%95%E7%89%87%E6%9C%BA%E5%AD%A6%E4%B9%A0%E2%80%94%E2%80%94ADC%E3%80%81PWM/" title="C51单片机学习——ADC/PWM"><img class="cover" src="http://xiaoziyan.top/images/f45614980b681dfbe655f12e7ba148cd.jpeg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2019-10-14</div><div class="title">C51单片机学习——ADC/PWM</div></div></a></div><div><a href="/xiaoziyan/2019/10/09/C51%E5%8D%95%E7%89%87%E6%9C%BA%E5%AD%A6%E4%B9%A0%E2%80%94%E2%80%94lcd1602%E6%B6%B2%E6%99%B6%E5%B1%8F/" title="C51单片机学习——lcd1602液晶屏"><img class="cover" src="http://xiaoziyan.top/images/3fe2d4f7f8aa0e706e4d555656cb673a.jpeg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2019-10-09</div><div class="title">C51单片机学习——lcd1602液晶屏</div></div></a></div><div><a href="/xiaoziyan/2019/10/11/C51%E5%8D%95%E7%89%87%E6%9C%BA%E5%AD%A6%E4%B9%A0%E2%80%94%E2%80%94%E5%A4%96%E9%83%A8%E4%B8%AD%E6%96%AD/" title="C51单片机学习——外部中断"><img class="cover" src="http://xiaoziyan.top/images/ac104f60351a347c48895f896bc64220.jpeg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2019-10-11</div><div class="title">C51单片机学习——外部中断</div></div></a></div><div><a href="/xiaoziyan/2019/10/08/C51%E5%8D%95%E7%89%87%E6%9C%BA%E5%AD%A6%E4%B9%A0%E2%80%94%E2%80%94%E6%8C%89%E9%94%AE%E6%8E%A7%E5%88%B6/" title="C51单片机学习——按键控制"><img class="cover" src="http://xiaoziyan.top/images/84c58abc41610ee19e1a478f91088e69.jpeg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2019-10-08</div><div class="title">C51单片机学习——按键控制</div></div></a></div><div><a href="/xiaoziyan/2019/10/06/C51%E5%8D%95%E7%89%87%E6%9C%BA%E5%AD%A6%E4%B9%A0%E2%80%94%E2%80%94%E6%B5%81%E6%B0%B4%E7%81%AF/" title="C51单片机学习——流水灯"><img class="cover" src="http://xiaoziyan.top/images/adb7f9eca04e6f962fe5f3e4a54d1d12.jpeg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2019-10-06</div><div class="title">C51单片机学习——流水灯</div></div></a></div><div><a href="/xiaoziyan/2019/10/13/C51%E5%8D%95%E7%89%87%E6%9C%BA%E5%AD%A6%E4%B9%A0%E2%80%94%E2%80%94%E8%AE%A1%E6%97%B6%E5%99%A8/" title="C51单片机学习——计时器"><img class="cover" src="http://xiaoziyan.top/images/993aef2c4e09cec3a090ec3a703eaa04.jpeg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2019-10-13</div><div class="title">C51单片机学习——计时器</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%80-IWDG%EF%BC%88%E7%8B%AC%E7%AB%8B%E7%9C%8B%E9%97%A8%E7%8B%97%EF%BC%89"><span class="toc-number">1.</span> <span class="toc-text">一.IWDG（独立看门狗）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BA%8C-%E7%AA%97%E6%88%B7%E7%9C%8B%E9%97%A8%E7%8B%97"><span class="toc-number">2.</span> <span class="toc-text">二.窗户看门狗</span></a></li></ol></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2022 By XiaoZiYan</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text"><p><a style="margin-inline:5px"target="_blank" href="https://hexo.io/"> <img src="https://img.shields.io/badge/Frame-Hexo-blue?style=flat&logo=hexo" title="博客框架为 Hexo" alt="HEXO"></a><a style="margin-inline:5px"target="_blank"href="https://butterfly.js.org/"> <img src="https://img.shields.io/badge/Theme-Butterfly-6513df?style=flat&logo=bitdefender" title="主题采用 Butterfly" alt="Butterfly"></a><a style="margin-inline:5px"target="_blank" href="https://www.jsdelivr.com/"> <img src="https://img.shields.io/badge/CDN-jsDelivr-orange?style=flat&logo=jsDelivr" title="本站使用 Jsdelivr 为静态资源提供CDN加速" alt="Jsdelivr"></a><a style="margin-inline:5px"target="_blank" href="https://github.com/"> <img src="https://img.shields.io/badge/Source-gitee-d021d6?style=flat&logo=Gitee" title="本站项目由 Gitee 托管" alt="Gitee"></a><a style="margin-inline:5px"target="_blank"href="http://creativecommons.org/licenses/by-nc-sa/4.0/"> <img src="https://img.shields.io/badge/Copyright-BY--NC--SA%204.0-d42328?style=flat&logo=Claris" alt="img" title="本站采用知识共享署名-非商业性使用-相同方式共享4.0国际许可协议进行许可"></a></p></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/xiaoziyan/js/utils.js"></script><script src="/xiaoziyan/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><script>function panguFn () {
  if (typeof pangu === 'object') pangu.autoSpacingPage()
  else {
    getScript('https://cdn.jsdelivr.net/npm/pangu/dist/browser/pangu.min.js')
      .then(() => {
        pangu.autoSpacingPage()
      })
  }
}

function panguInit () {
  if (false){
    GLOBAL_CONFIG_SITE.isPost && panguFn()
  } else {
    panguFn()
  }
}

document.addEventListener('DOMContentLoaded', panguInit)</script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"></div><script src="./js/sakura.js"></script><canvas class="fireworks" mobile="false"></canvas><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/fireworks.min.js"></script><script defer="defer" id="ribbon" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-ribbon.min.js" size="150" alpha="0.6" zIndex="-1" mobile="false" data-click="true"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><!-- hexo injector body_end start --><script data-pjax>function electric_clock_injector_config(){
                var parent_div_git = document.getElementsByClassName('sticky_layout')[0];
                var item_html = '<div class="card-widget card-clock"><div class="card-glass"><div class="card-background"><div class="card-content"><div id="hexo_electric_clock"><img id="card-clock-loading" src="https://cdn.jsdelivr.net/gh/Zfour/Butterfly-clock/clock/images/weather/loading.gif" style="height: 120px; width: 100%;" data-ll-status="loading" class="entered loading"></div></div></div></div></div>';
                console.log('已挂载electric_clock')
                // parent_div_git.innerHTML=item_html+parent_div_git.innerHTML // 无报错，但不影响使用(支持pjax跳转)
                parent_div_git.insertAdjacentHTML("afterbegin",item_html) // 有报错，但不影响使用(支持pjax跳转)
            }if( document.getElementsByClassName('sticky_layout')[0] && (location.pathname ==='all'|| 'all' ==='all')){

            electric_clock_injector_config()
        } </script><script src="https://pv.sohu.com/cityjson?ie=utf-8"></script><script data-pjax  src="https://cdn.jsdelivr.net/gh/Zfour/hexo-electric-clock@1.0.6/clock.js"></script><!-- hexo injector body_end end --></body></html>